<?php

namespace july\julyadmin\builder\traits\actions;

/**
 * 导入
 */
trait HasImport
{
    //每次导入多少条
    protected $importLimit = 500;
    /**
     * 导入
     * @Author   july
     * @DateTime 2023-09-04
     * @param    string     $page             第几页
     * @param    string     $url              导入文件地址
     */
    public function import($page = 1, $url = '')
    {
        if (request()->isPost()) {
            ini_set('max_execution_time', 0);
            if (!file_exists('.' . $url)) {
                $this->error('导入的文件不存在');
            }

            $fileParts = pathinfo('.' . $url);
            $ext       = strtolower($fileParts['extension']);
            if (!in_array($ext, ['xls', 'xlsx', 'csv'])) {
                $this->error('不支持的文件');
            }
            $importLogic = new \july\julyadmin\common\logic\ImportLogic('.' . $url);
            $result      = $importLogic->import($page, $this->importLimit);

            $result['data']['page']     = $page;
            $result['data']['pages']    = ceil($result['data']['total'] / $this->importLimit);
            $result['data']['progress'] = min(100, ceil($page / $result['data']['pages'] * 100));

            $import_result = $this->importSuccess($page, $result['data']);
            if (!isset($import_result['code'])) {
                $this->error('返回格式错误');
            }
            if ($import_result['code'] != 1) {
                return json($import_result);
            }
            return json($result);
        } else {
            $import_url = url(request()->controller() . "/import");
            $script     = <<<EOT
        <script>
            // 导入
            // page: 1，第一次点击必须是1
            // url:要导入的文件地址
            function tableImport(page,url){
                if(page==1){
                    layui.element.progress('import-filter-progress', '0%');
                }
                $.ajax({
                    type:'POST',
                    url:'{$import_url}',
                    data:{
                        page:page,
                        url:url
                    },
                    dataType:'json',
                    success:function(res) {
                        //设置进度
                        if(res.hasOwnProperty("code") && res.code==1){
                            layui.element.progress('import-filter-progress', res.data.progress+'%');
                            if(parseInt(page)<res.data.pages){
                                tableImport(parseInt(page)+1,url);
                            }
                            if(res.data.progress>=100){
                                parent.layer.alert(res.msg, {
                                    icon: 6,
                                    shadeClose: true,
                                });
                                parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页 
                            }
                        }else{
                            layer.close(window.import_window);
                            parent.layer.alert(res.hasOwnProperty('msg') && res.msg?res.msg:'操作失败！', {
                                icon: 5,
                                shadeClose: true,
                            });
                            parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页 
                        }
                    },
                    error:function(res){
                        layer.close(window.import_window);
                        parent.layer.alert(JSON.stringify(res), {
                            icon: 5,
                            shadeClose: true,
                        });
                        parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页 
                    }
                });
            }

            var url = '';
            var time = setInterval(function(){
                if($('#url_input').val() && $('#url_input').val()!=url){
                    clearInterval(time);
                    url = $('#url_input').val();
                    var layui$ = layui.$;
                    layui$('form label').html('进度');
                    // 动态插入进度条元素
                    layui$('form div div').html(`
                        <div class="layui-progress layui-progress-big" lay-showPercent="true" lay-filter="import-filter-progress">
                          <div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
                        </div>
                    `);
                    // 渲染进度条组件
                    layui.element.render('progress', 'import-filter-progress');
                    tableImport(1,url);
                }
            },500);
            $('form').css('--bs-gutter-x','auto');
            $('.container-fluid').css('padding-right','0px !important');
            $('#url_input').attr('disabled',true);
            $(".form-btns").remove();

        </script>


EOT;
            $style = <<<EOT

            <style>
                .row>*{
                    padding-right:0px !important;
                }
                body{
                    padding:0px;
                }
                .card-body{
                    padding:20px;
                }
            </style>

EOT;
            $builder = $this->builder();
            $form    = new \july\julyadmin\builder\Form($builder, '');
            $form->script($script)->style($style);
            $form->show('file', 'url', 'xls,xlsx,csv')->setExt('xls,xlsx,csv')->showFileList(false)->setSelectServerFile(false);
            $form->render();
            exit;
        }
    }

    /**
     * 导入文件读取完成执行这里，可以重写这个方法，把data中的数据写到数据库
     * @Author   July
     * @DateTime 2023-10-13T20:56:54+0800
     * @param    integer                  $page 第几页
     * @param    array                    $data excel或者csv数据列表
     * @return   array                    ['code'=>1|0,'msg'=>'']
     */
    protected function importSuccess($page = 1, $data = [])
    {
        return ['code' => 0, 'msg' => "请在控制器中重写importSuccess(\$page = 1,\$data = [])方法，将data中的数据写入数据库，然后返回成功['code'=>1,'msg'=>'']或者失败['code'=>0,'msg'=>'上传失败信息']"];
    }
}
